package com.mentalsurvey.controller;

import com.mentalsurvey.entity.User;
import com.mentalsurvey.mapper.UserMapper;
import com.mentalsurvey.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author vito
 * @version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserMapper userMapper;

    //登录
    @PostMapping("/login")
    public Result<String> getLogin(@RequestBody User user) {
        User u = userMapper.getUserById(user.getUsername());
        if (u != null) {
            if (u.getPassword().equals(user.getPassword())) {
                return Result.success("登录成功");
            } else {
                return Result.error("账号或密码错误");
            }
        }
        return Result.error("账号或密码错误");
    }

    //注册
    @PostMapping("/register")
    public Result<String> register(@RequestBody User user) {
        // 1. 检查用户名是否存在
        User existingUser = userMapper.getUserById(user.getUsername());
        if (existingUser != null) {
            return Result.error(400, "用户名已存在");
        }

        // 2. 简单密码校验（建议做更多处理）
        if (user.getPassword() == null || user.getPassword().length() < 6) {
            return Result.error(400, "密码不能少于6位");
        }

        // 3. 插入数据库
        int rows = userMapper.register(user);
        if (rows > 0) {
            return Result.success("注册成功", null);
        } else {
            return Result.error(500, "注册失败");
        }
    }

}
